
#include <QtCore>
#include <QtGui>
#include <QtNetwork>

#include "RssBrowsing.h"
#include <ctype.h>
#include <iostream>

using namespace std;

Item::Item()
{
        myItemFormat.imageAvailable = false;
}

Item::~Item()
{
}

void Item::print()
{
        cout<< "cardUrl  '" <<getItemAsStructure().cardUrl << "'"<<endl;
        cout<< "imageUrl  '" <<getItemAsStructure().imageUrl << "'"<<endl;
        cout<< "itemDescription  '" <<getItemAsStructure().itemDescription << "'"<<endl;
        cout<< "itemTitle  '" <<getItemAsStructure().itemTitle << "'"<<endl;
        cout<< "ImageAvailable:  '" <<getItemAsStructure().imageAvailable << "'"<<endl;
}


string Item::getItemTitle()
{
        return myItemFormat.itemTitle;
}

string Item::getItemDescription()
{
        return myItemFormat.itemDescription;
}

string Item::getImageUrl()
{
        return myItemFormat.imageUrl;
}

string Item::getCardUrl()
{
        return myItemFormat.cardUrl;
}

bool Item::isImageAvailable()
{
        return myItemFormat.imageAvailable;
}

void Item::updateItem(std::string itemTitleS, std::string itemDescriptionS, std::string imageUrlS, std::string cardUrlS)
{
        myItemFormat.itemTitle = itemTitleS;
        myItemFormat.itemDescription = itemDescriptionS;
        myItemFormat.imageUrl = imageUrlS;
        myItemFormat.cardUrl = cardUrlS;
        if(myItemFormat.imageUrl.empty()) myItemFormat.imageAvailable = false;
        else myItemFormat.imageAvailable = true;
}

itemFormat Item::getItemAsStructure()
{
        return myItemFormat;
}

//---------------------------------------------------------------------------------------------
// RSSBROWSING Class

RssBrowsing::RssBrowsing(string key, QWidget *parent)
    : QWidget(parent)
{
        items = new Item[10];
        for(unsigned int i=0; i<= key.length(); i++){
            keyWord.append(1,(char)toupper(key[i]));
        }

        lineEdit = new QLineEdit(this);
        lineEdit->setText("Politics");

        fetchButton = new QPushButton(tr("Fetch"), this);
        abortButton = new QPushButton(tr("Abort"), this);
        printButton = new QPushButton(tr("Print"), this);

        abortButton->setEnabled(false);

        connect(&http, SIGNAL(readyRead(const QHttpResponseHeader &)),
              this, SLOT(readData(const QHttpResponseHeader &)));

        connect(&http, SIGNAL(requestFinished(int, bool)),
              this, SLOT(finished(int, bool)));

        connect(lineEdit, SIGNAL(returnPressed()), this, SLOT(fetch()));
        connect(fetchButton, SIGNAL(clicked()), this, SLOT(fetch()));
        connect(abortButton, SIGNAL(clicked()), &http, SLOT(abort()));
        connect(printButton, SIGNAL(clicked()), this, SLOT(print()));

        QVBoxLayout *layout = new QVBoxLayout(this);
        QHBoxLayout *hboxLayout = new QHBoxLayout;

        hboxLayout->addWidget(lineEdit);
        hboxLayout->addWidget(fetchButton);
        hboxLayout->addWidget(abortButton);
        hboxLayout->addWidget(printButton);

        layout->addLayout(hboxLayout);

        setWindowTitle(tr("RSS Example"));
        resize(640,50);


}

RssBrowsing::~RssBrowsing()
{
       if(items != NULL) delete items;
}


Item RssBrowsing::getItemByNumber(int number)
{
        if((1 <= number) && (number <= 10)) return items[number-1];
        else return Item();
}


void RssBrowsing::fetch()
{
        lineEdit->setReadOnly(true);
        fetchButton->setEnabled(false);
        abortButton->setEnabled(true);
        printButton->setEnabled(false);

        xml.clear();
        QUrl url;

        string text =lineEdit->text().toStdString();

        if (!text.empty()){
            for(unsigned int i=0; i<= text.length(); i++){
                keyWord.append(1,(char)toupper(text[i]));
            }
         }

        if(!keyWord.compare("POLITICS")) url.setUrl((QString("http://rss.news.yahoo.com/rss/politics")));
        else if(!keyWord.compare("TECHNOLOGY")) url.setUrl(QString("http://rss.news.yahoo.com/rss/tech"));
        else if(!keyWord.compare("TRAVEL"))  url.setUrl(QString("http://rss.news.yahoo.com/rss/tech"));
        else if(!keyWord.compare("ENTERTAINMENT")) url.setUrl(QString("http://rss.news.yahoo.com/rss/entertainment"));
        else if(!keyWord.compare("SPORTS"))  url.setUrl(QString("http://rss.news.yahoo.com/rss/sports"));
        else  url.setUrl(QString("http://rss.news.yahoo.com/rss/topstories"));

        http.setHost(url.host());
        connectionId = http.get(url.path());

}


void RssBrowsing::readData(const QHttpResponseHeader &resp)
{
    if (resp.statusCode() != 200)
        http.abort();
    else {
        xml.addData(http.readAll());
        parseXml();
    }
}


void RssBrowsing::parseXml()
{
        int i = 0;
        QString currentTag;
        while (!xml.atEnd() && i<10) {
         xml.readNext();
         if (xml.isStartElement()) {
             //if (xml.name() == "item") linkString = xml.attributes().value("rss:about").toString();
             currentTag = xml.name().toString();
         } else if (xml.isEndElement()) {
             if (xml.name() == "item") {
                                 if(items[i].getItemAsStructure().imageUrl.empty())items[i].getItemAsStructure().imageAvailable = false;
                                 else items[i].getItemAsStructure().imageAvailable = true;
                                 i++;
             }

         } else if (xml.isCharacters() && !xml.isWhitespace()) {
             if (currentTag == "title")
                 items[i].getItemAsStructure().itemTitle += xml.text().toString().toStdString();
             else if (currentTag == "link")
                                 items[i].getItemAsStructure().cardUrl += xml.text().toString().toStdString();
                         else if (currentTag == "description")
                                 items[i].getItemAsStructure().itemDescription += xml.text().toString().toStdString();
                         else if (currentTag == "media:content"){
                                 items[i].getItemAsStructure().imageUrl += xml.attributes().value("url").toString().toStdString();
                                 string::size_type pos;
                                 pos = items[i].getItemAsStructure().imageUrl.find_first_of('?');
                                 if(pos != string::npos) items[i].getItemAsStructure().imageUrl.erase(pos+1);
                         }
         }
        }

     if (xml.error() && xml.error() != QXmlStreamReader::PrematureEndOfDocumentError) {
         qWarning() << "XML ERROR:" << xml.lineNumber() << ": " << xml.errorString();
         http.abort();
         }

}


void RssBrowsing::finished(int id, bool error)
 {
     if (error) {
         qWarning("Received error during HTTP fetch.");
         lineEdit->setReadOnly(false);
         abortButton->setEnabled(false);
         fetchButton->setEnabled(true);
         printButton->setEnabled(true);
     }
     else if (id == connectionId) {
         lineEdit->setReadOnly(false);
         abortButton->setEnabled(false);
         fetchButton->setEnabled(true);
         printButton->setEnabled(true);
     }
 }

void RssBrowsing::print()
{
    for(int i=0; i<10; i++)
        {
                cout<< "--- ITEM " << i+1 << " ---"<<endl;
                getItemByNumber(i+1).print();
        }
}

